<template>
	<view class="container">
		<view class="">
			当前已连接设备:{{LastDeviceName}}
		</view>
		<view @tap="searchBle">搜索打印设备（需开启蓝牙）</view>
		<!-- <view>清空所有缓存蓝牙设备</view> -->
		<view @click="testPrint">测试打印</view>
		<!-- <view @tap="test">测试普通打印连接</view> -->
		<!-- <view class="break">断开连接</view> -->
			<view class="set">
			<view @tap="setDefault(1)" :class="['ticket',contentFlag==1?'click':'']"> 设置当前打印标签 </view>
			<view @tap="setDefault(2)" :class="['ticket',contentFlag==2?'click':'']"> 设置当前打印小票 </view>
		</view>
		<!-- {{list}} -->
		<view v-for="(item,index) in devices" :key="item.deviceId">
			<view class="item">
				<view class="deviceId block">{{ item.deviceId }}</view>
				<view class="name block">设备名称:{{ item.name }}</view><!-- 信号强度: {{ item.RSSI }}dBm -->
				<view class="content"  @click="cneertOrClose(item)"> {{item.deviceId== deviceId?'断开':'连接'}} </view>
				<!-- <view v-show="!item.connetFlag" class="content" @click="destroyed(item,index)"> 断开 </view> -->
			</view>
		</view>
		<!-- <view style="margin-top: 30upx;" :key="index" v-for="(item,index) in devices">
			<button style="width: 400upx; color: #0081FF;" @click="onConn(item)">{{item.name}}</button>
		</view> -->
	</view>
</template>

<script>
	// #ifndef MP-WEIXIN
	import ReplceInfo from "../../utils/repleceInfo.js"
	// #endif


	var app = getApp(); 
	export default {
		data() {
			return {
				devices: [],
				services: [],
				deviceId: '',
				LastDeviceName: "无",
				serviceId: 0,
				writeCharacter: false,
				readCharacter: false,
				notifyCharacter: false,
				contentFlag:null
			};
		},
		onShow() {
			// uni.removeStorageSync('contentFlag')
			// this.contentFlag=null
			this.contentFlag=uni.getStorageSync('contentFlag')
			// console.log(JSON.parse(uni.getStorageSync('Bluetooth')))
			if (uni.getStorageSync('deviceName')) {
				this.LastDeviceName =uni.getStorageSync('deviceName');
				this.deviceId =uni.getStorageSync('deviceId');
			}
			else
			{
				this.LastDeviceName = '无';
			}
		},
		onLoad: function() {
		},
		onUnload(){
			uni.hideLoading()
		},
		
		methods: {
			setDefault(type){
				uni.setStorageSync('contentFlag',type)
				this.contentFlag=type
			},
			destroyed: function(item) {
				let that = this;
				if (that.deviceId != '') {
					uni.closeBLEConnection({
						deviceId: that.deviceId,
						success(res) {
							// that.$set(that.devices[index], that.devices[index].connetFlag, true)
							item.connetFlag=!item.connetFlag;
							that.LastDeviceName = '无';
							that.deviceId = '';
							uni.removeStorageSync('deviceName')
							uni.removeStorageSync('deviceId')
							that.$forceUpdate()
							uni.showToast({
								title:"断开成功"
							})
							
						}
					})
				}

			},
			setData() {

			},
			cneertOrClose(item){
				if(this.deviceId == item.deviceId)
				{
					this.destroyed(item);
				}
				else
				{
					this.connectBluetooth(item);
				}
			},
			// 测试打印
			testPrint() {
				// #ifndef MP-WEIXIN
				var jpPrinterObj = ReplceInfo.jpPrinterObj.createNew();
				jpPrinterObj.testPrint();
				console.log('testPrint');
				// #endif
				
			},
			//搜索设备
			searchBle: function() {
				console.log('我进来了')
				uni.showLoading({
					title:"正在搜索蓝牙设备"
				})
				var that = this;
				uni.openBluetoothAdapter({
					success: function(res) {
						uni.getBluetoothAdapterState({
							success: function(res) {
								console.log("openBluetoothAdapter success", res);

								if (res.available) {
									if (res.discovering) {
										uni.stopBluetoothDevicesDiscovery({
											success: function(res) {
												console.log(res);
											}
										});
									} else {
										// that.startBluetoothDevicesDiscovery()
										that.getBluetoothDevices();
									} // that.checkPemission()
								} else {
									uni.showModal({
										title: "提示",
										content: "本机蓝牙不可用",
										showCancel: false
									});
								}
							}
						});
					},
					fail: function() {
						uni.showModal({
							title: "提示",
							content: "蓝牙初始化失败，请到设置打开蓝牙",
							showCancel: false
						});
					}
				});
			},
			// 获取蓝牙信息
			getBluetoothDevices: function() {
				//获取蓝牙设备信息
				var that = this;
				console.log("start search");
				
				uni.startBluetoothDevicesDiscovery({
					success: function(res) {
						console.log(res);
						setTimeout(function() {
							uni.getBluetoothDevices({
								success: function(res) {
									var devices = [];
									var num = 0;

									for (var i = 0; i < res.devices.length; ++i) {
										// console.log("res.devices[i].name"+res.devices[i].name);
										if ((res.devices[i].name != "未知设备") && (res.devices[i].name != "")) {
											devices[num] = res.devices[i];
											num++;
										}
									}
									that.devices = devices;
									uni.hideLoading();
									// uni.stopPullDownRefresh();
									uni.stopBluetoothDevicesDiscovery({
										success: function(res) {
											// console.log("停止搜索蓝牙");
										}
									});
								}
							});
						}, 2000);
					}
				});
			},
			// 停止搜索
			stopFindBule() {

				uni.stopBluetoothDevicesDiscovery({
					success(res) {
						
					}
				})
			},
			// 连接
			connectBluetooth(item) {
				uni.setStorageSync("content",item)
				console.log(item)
				// return
				uni.setStorageSync("deviceId",item)
				var that = this;
				uni.stopBluetoothDevicesDiscovery({
					success: function(res) {
						// console.log(res);
					}
				});
				that.serviceId = 0;
				let deviceId = item.deviceId;
				
				uni.showLoading({
					title: "正在连接"
				});
				uni.createBLEConnection({
					deviceId: deviceId,
					complete(res) {
						console.log(res)
						if (res.errMsg == "createBLEConnection:ok") {
							// console.log("连接蓝牙-[" + item.name + "]--成功")
							uni.showToast({
								title: `连接蓝牙-${item.name}-成功`,
								icon: "none"
							})
							
							
						
							//记录当前链接的蓝牙设备
							// that.devices[index].connetFlag=false
							that.deviceId = deviceId;
							app.globalData.BLEInformation.deviceId = deviceId;
							uni.setStorageSync('deviceId',deviceId)
							uni.setStorageSync('deviceName',item.name)
							that.LastDeviceName = item.name;
							// uni.setStorageSync('Bluetooth',JSON.stringify({currDev:item}));
							that.currDev = item;
							setTimeout(function() {
								that.getBLEServices(deviceId);
								// uni.hideLoading()
							}, 2000)
						} else {
							console.log(res)
							uni.showToast({
								title:"连接失败",
								icon:"none"
							})
						}
						//连接成功 关闭搜索!
						that.stopFindBule()

					},
				})
			},
			// 获取特征值
			getBLEServices(_deviceId) {
				var that = this;
				uni.getBLEDeviceServices({
					deviceId: _deviceId,
					success: function(res) {
						that.services = res.services;
						// console.log('that.services = ' + that.services);
						that.getCharacteristics();
						// uni.navigateBack()
					},
					fail: function(e) {
						// console.log(e);
					},
					complete: function(e) {
						// console.log(e);
					}
				});

			},
			getCharacteristics: function() {
				var that = this;
				var list = that.services;
				// console.log(list);
				if(list && (list.length <=0))
				{
					that.getBLEServices(that.deviceId);
					return;
				}
				var num = that.serviceId;
				var write = that.writeCharacter;
				var read = that.readCharacter;
				var notify = that.notifyCharacter;
				uni.getBLEDeviceCharacteristics({
					deviceId: uni.getStorageSync('deviceId'),
					serviceId: list[num].uuid,
					success: function(res) {
						// console.log(res);
						var characteristics = res.characteristics;
						for (var i = 0; i < characteristics.length; ++i) {
							var properties = characteristics[i].properties;
							var uuid = characteristics[i].uuid;

							if (!notify) {
								if (properties.notify) {
									app.globalData.BLEInformation.notifyCharaterId = uuid;
									app.globalData.BLEInformation.notifyServiceId = list[num].uuid;
									uni.setStorageSync('notifyCharaterId',uuid)
									uni.setStorageSync('notifyServiceId',list[num].uuid)
									notify = true;
								}
							}

							if (!write) {
								if (properties.write) {
									app.globalData.BLEInformation.writeCharaterId = uuid;
									app.globalData.BLEInformation.writeServiceId = list[num].uuid;
									uni.setStorageSync('writeCharaterId',uuid)
									uni.setStorageSync('writeServiceId',list[num].uuid)
									write = true;
								}
							}

							if (!read) {
								if (properties.read) {
								app.globalData.BLEInformation.readCharaterId = uuid;
								app.globalData.BLEInformation.readServiceId = list[num].uuid;
									uni.setStorageSync('readCharaterId',uuid)
									uni.setStorageSync('readServiceId',list[num].uuid)
									read = true;
								}
							}
						}

						if (!write || !notify || !read) {
							num++;
							that.writeCharacter = write;
							that.readCharacter = read;
							that.notifyCharacter = notify;
							that.serviceId = num;

							if (num == list.length) {
								uni.showModal({
									title: "提示",
									content: "找不到该读写的特征值",
									showCancel: false
								});
							} else {
								that.getCharacteristics();
							}
						} else {
							uni.hideLoading()
							let contentFlag = uni.getStorageSync('content')
							if(!contentFlag){
								uni.navigateBack({
									delta:1
								})
							}
							
							// uni.showToast({
							// 	title: "连接成功"
							// });
							// 连接成功
						}
					},
					fail: function(e) {
						// console.log(e);
					},
					complete: function(e) {
						// console.log("write:" + app.globalData.BLEInformation.writeCharaterId);
						// console.log("read:" + app.globalData.BLEInformation.readCharaterId);
						// console.log("notify:" + app.globalData.BLEInformation.notifyCharaterId);
					}
				});
			},
			closeCont(){
				console.log('我进来了')
				// uni.closeBluetoothAdapter({
				// 	success() {
				// 		this.deviceId="";
				// 		uni.showToast({
				// 			title:"断开成功!",
				// 			icon:"none"
				// 		})
				// 	}
				// })
			}
		}

	};
</script>

<style scoped lang="scss">
	page {
		background-color: #f1f1f1;
	}

	.container {
		height: 100vh;
		background: #f1f1f1;
		padding: 25rpx 18rpx;

		&>view {
			background-color: #fff;
			margin-bottom: 6rpx;
			border-radius: 20rpx;
			// height: 90rpx;
			line-height: 90rpx;
			text-align: center;
		}

		.break {
			margin-top: 30rpx;
			margin-bottom: 18rpx;
		}

		.set {
			display: flex;
			justify-content: space-between;
			background-color: #f1f1f1;
			margin-bottom: 75rpx;
			margin-top: 50rpx;

			view {
				box-sizing: border-box;
				border-radius: 20rpx;
				padding: 35rpx 67rpx;
				width: 318rpx;
				line-height: 35rpx;
				background: #fff;
			}

			.click {
				background: #fe3430;
				color: #fff;
			}
		}

		.cu-btn {
			height: 80rpx;
			color: #ffffff;
			font-size: 30rpx;
			margin-bottom: 20rpx;
			background-color: #06d078;
		}

		.content {
			background: #fe3430;
			// padding: 10rpx;
			border-radius: 10rpx;
			width: 200rpx;
			margin: auto;
			color: #fff;
		}

		.item-wrap {
			display: flex;
			align-items: center;
			justify-content: space-between;
			color: #06d078;
			padding: 10rpx;
			margin-bottom: 20rpx;
			border-radius: 8rpx;
			border: 4rpx solid #c8c7cc;
		}

		.connect-button {
			height: 60rpx;
			color: #ffffff;
			font-size: 30rpx;
			margin-right: 30rpx;
			background-color: #06d078;
		}

		.loading-icon {
			animation: turn 1s linear infinite;
		}

		@keyframes turn {
			0% {
				-webkit-transform: rotate(0deg);
			}

			25% {
				-webkit-transform: rotate(90deg);
			}

			50% {
				-webkit-transform: rotate(180deg);
			}

			75% {
				-webkit-transform: rotate(270deg);
			}

			100% {
				-webkit-transform: rotate(360deg);
			}
		}
	}
</style>
